package com.aida.evil.eda.Answer;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Adapter.CommonAdapter;
import com.aida.evil.eda.Adapter.ViewHolder;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.Login.Encryp_AES;
import com.aida.evil.eda.MyView.CircleTextView;
import com.aida.evil.eda.MyView.ListViewForScrollView;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.aida.evil.eda.WebView.WebViewActivity;
import com.aida.evil.eda.Window.CustomDialog;
import com.aida.evil.eda.fragment.Eda;
import com.dd.CircularProgressButton;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/********************************************
 * 工程名：Aida
 * 包名：com.aida.evil.eda.Answer
 * 时间：16-5-1 上午11:44
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：
 ********************************************/
public class AnswerItemFragment extends Fragment
{
    /*加载item图片内容*/
    private static final String IMGURL =
            "http://" + NetworkData.ServiceIP + "/ItemImg?ItemImg=";
    /*流量提交*/
    private static final String SUBMITURL = "http://" + NetworkData.ServiceIP + "/AnswerResult";

    private int position;/*此题在题目集的位置 0开始*/
    private int size;/*题目集大小 1开始*/
    private int yesNum;


    private View view;/*总视图*/
    private ImageView imageView;/*题目展示图片*/
    private ListViewForScrollView listView;/*题目答案选项*/
    private TextView question_TextView;/*题目问题*/

    private int itemID;
    private int listView_position;
    private String id;
    private String imgPath;
    private String question;
    private String yes;
    private String[] no;
    private String briefUrl;
    private int flow;

    private CircularProgressButton submit_button;/*提交按钮*/

    private ArrayList<String> choose_List = new ArrayList<>();/*选项内容集合*/

    public AnswerItemFragment()
    {
    }

    public static AnswerItemFragment newInstance(int itemID2, int listView_position2, int position2, int size2, String id2
            , String imgPath2, String question2, String yes2, String[] no2
            , String briefUrl2, int flow2)
    {
        AnswerItemFragment answerItemFragment = new AnswerItemFragment();
        if (Answer.flowList == null)
            Answer.flowList = new ArrayList<>();
        if (Answer.selectList == null)
            Answer.selectList = new SparseArray<>();
        if (Answer.answerChoose == null)
            Answer.answerChoose = new SparseArray<>();


        answerItemFragment.position = position2;
        answerItemFragment.size = size2;
        answerItemFragment.itemID = itemID2;
        answerItemFragment.listView_position = listView_position2;
        answerItemFragment.id = id2;
        answerItemFragment.imgPath = imgPath2;
        answerItemFragment.question = question2;
        answerItemFragment.yes = yes2;
        answerItemFragment.no = no2;
        answerItemFragment.briefUrl = briefUrl2;
        answerItemFragment.flow = flow2;

        Answer.flowList.add(flow2);
        Answer.answerChoose.put(answerItemFragment.position, false);

        return answerItemFragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.answer_fragment, container, false);
        initView();/*初始化视图*/
        setSubmitButton();/*如果此题是题目集最后一道，显示提交按钮*/
        setImageView();/*设置题目展示图片*/
        setListView();/*设置题目内容*/
        setListViewOnClick();/*设置ListView点击监听*/

        return view;
    }


    /**
     * 初始化视图
     */
    private void initView()
    {
        imageView = (ImageView) view.findViewById(R.id.answer_imageView);
        listView = (ListViewForScrollView) view.findViewById(R.id.answer_listView);
        question_TextView = (TextView) view.findViewById(R.id.answer_question);
        submit_button = (CircularProgressButton) view.findViewById(R.id.answer_submit);
        submit_button.setIndeterminateProgressMode(true);
    }


    /**
     * 设置题目展示图片
     */
    private void setImageView()
    {
        if (!imgPath.equals(""))
            Picasso.with(getContext()).load(IMGURL + imgPath).into(imageView);

        /*设置图片监听，跳转到详情WebView页面*/
        imageView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url", briefUrl);
                startActivity(intent);
            }
        });
    }

    /**
     * 设置提交按钮
     */
    private void setSubmitButton()
    {
        if (position + 1 == size)
        {
            submit_button.setVisibility(View.VISIBLE);
            submit_button.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    int flowSum = 0;/*流量总和*/
                    yesNum = 0;/*正确个数*/
                    if (submit_button.getProgress() == -1 || submit_button.getProgress() == 100)
                    {
                        submit_button.setProgress(0);
                    }
                    else
                    {
                        if (Answer.answerChoose.size() != 0)
                        {
                            submit_button.setProgress(50);

                            for (int i = 0; i < size; i++)
                            {
                                if (Answer.answerChoose.get(i, false))
                                {
                                    flowSum += Answer.flowList.get(i);
                                    yesNum++;
                                }
                            }
                            toNetWork(flowSum, yesNum, size);/*上传积分数据*/
                        }
                    }
                    /*发送广播*/
                    {
                        Intent intent = new Intent();
                        intent.setAction(Eda.EDA_ACTION);
                        intent.putExtra("position", listView_position);
                        getContext().sendBroadcast(intent);
                        Log.i("发送", listView_position + "");
                    }
                }
            });
        }
    }

    /**
     * 网络加载，上传积分流量数据
     */
    private void toNetWork(final int flowSum, int yesNum, int size)
    {
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            @Override
            public void reqSuccess(String response)
            {
                success(response, flowSum);
            }

            @Override
            public void reqError(String error)
            {
                submit_button.setProgress(-1);
            }
        };
        Map<String, String> map = new HashMap<>();
        map.put("userPhoneNum", UserData.DATA_PHONENUM);
        map.put("itemID", AnswerActivity.itemID + "");
        map.put("over", 0 + "");/*0为全部完成,1为未全部完成*/
        map.put("flowSum", Encryp_AES.getAESCode(flowSum + ""));
        map.put("yesNum", yesNum + "");
        map.put("size", size + "");
        VolleyHttpRequest.String_request(SUBMITURL, map, stringVolleyHandler);
    }

    /**
     * 处理网络请求成功后的事件
     */
    private void success(String response, int flowSum)
    {
        /*请求成功*/
        if (response.equals("1"))
        {
            submit_button.setProgress(100);
            Intent intent = new Intent(getActivity(), AnswerResult.class);
            intent.putExtra("flowSum", Encryp_AES.getAESCode(Encryp_AES.getAESCode(flowSum + "")));
            intent.putExtra("yes", yesNum);
            intent.putExtra("size", size);
            startActivity(intent);
            AnswerActivity.viewPager.removeAllViews();
            getActivity().finish();
            Answer.answerChoose = null;
            Answer.selectList = null;
            Answer.flowList = null;
        }
        /*请求失败*/
        else if (response.startsWith("ERROR:"))
        {
            submit_button.setProgress(-1);
            if (response.endsWith("CHEAT"))
            {
                final CustomDialog.Builder builder = new CustomDialog.Builder(getContext());
                builder.setTitle("警告！");
                builder.setMessage("您有作弊行为，请规范您的操作，否则将会进行惩罚！");
                builder.setBackPressed(false);
                builder.setCanceledOnTouchOutside(false);
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        builder.dismiss();
                        new Answer.showDialog(getActivity())
                        {
                            @Override
                            public void clear()
                            {
                                flow = 0;
                                choose_List.clear();
                            }
                        }.finish();
                    }
                });
                builder.show();
            }
            else
            {
                String s = response.replace("ERROR:", "");
                final CustomDialog.Builder builder = new CustomDialog.Builder(getContext());
                builder.setTitle("提示");
                builder.setMessage("您已经在" + s + "提交过该题目，请勿重复提交！");
                builder.setBackPressed(false);
                builder.setCanceledOnTouchOutside(false);
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        builder.dismiss();
                        new Answer.showDialog(getActivity())
                        {
                            @Override
                            public void clear()
                            {
                                flow = 0;
                                choose_List.clear();
                            }
                        }.finish();
                    }
                });
                builder.show();
            }
        }
    }

    /**
     * 设置题目内容
     */
    private void setListView()
    {
        /*设置问题*/
        {
            question_TextView.setText("     " + question);
            question_TextView.setTextSize(18);
        }
        /*设置选项*/
        {
            if (choose_List.size() == 0)
            {
                choose_List.add(yes);
                for (int i = 0; i < no.length; i++)
                {
                    choose_List.add(no[i]);
                }
                Collections.shuffle(choose_List);//将arraylist数组乱序排列
            }


            ArrayList<Bean> been_List = new ArrayList<>();
            for (int i = 0; i < choose_List.size(); i++)
            {
                been_List.add(new Bean(" " + (char) (i + 'A'), choose_List.get(i)));
            }
            /*设置ListView*/
            {
                Adapter adapter = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                {
                    adapter = new Adapter(getContext(), been_List, R.layout.answer_listview_item);
                    listView.setSelector(R.color.pblue);/*设置选中的颜色*/
                }
                else
                {
                    adapter = new Adapter(getContext(), been_List, R.layout.answer_listview_item_4_4);
                    listView.setSelector(R.drawable.answer_listview_item1);/*设置选中的颜色*/
                }
                listView.setAdapter(adapter);
            }
        }
    }

    /**
     * 设置选项点击监听
     */

    private void setListViewOnClick()
    {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int item_position, long id)
            {
                Answer.selectList.put(position, item_position);/*设置选项，防止Fragment重新加载答案消失*/
                {
                    if (choose_List.get(item_position).equals(yes))
                        Answer.answerChoose.put(position, true);
                    else
                        Answer.answerChoose.put(position, false);
                }
            }
        });

    }


    /*****************************************
     * 内部类
     */
    private class Adapter extends CommonAdapter<Bean>
    {

        public Adapter(Context context, List<Bean> itemBean_list, int itemLayoutResId)
        {
            super(context, itemBean_list, itemLayoutResId);
        }

        @Override
        public void convert(ViewHolder viewHolder, Bean item)
        {
            CircleTextView circleTextView = viewHolder.getView(R.id.answer_listView_item_circleTextView);
            TextView textView = viewHolder.getView(R.id.answer_listView_item_textView);
            circleTextView.setText(item.choose);
            textView.setText(item.choose_context);

            /**
             * 如果Fragment重建，设置选择选项
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            {
                if (Answer.selectList.size() > position)
                {
                    if (viewHolder.position == Answer.selectList.get(position))
                    {
                        viewHolder.getConvertView().setBackgroundResource(R.color.pblue);
                    }
                    else
                    {
                        viewHolder.getConvertView().setBackgroundResource(R.color.white);
                    }
                }
            }
            else
            {
                if (Answer.selectList.size() > position)
                {
                    if (viewHolder.position == Answer.selectList.get(position))
                    {
                        viewHolder.getConvertView().setBackgroundResource(R.drawable.answer_listview_item1);
                    }
                    else
                    {
                        viewHolder.getConvertView().setBackgroundResource(R.drawable.answer_listview_item2);
                    }
                }
            }
        }
    }

    /**
     * ListView的Bean
     */
    private class Bean
    {
        public Bean(String choose, String choose_context)
        {
            this.choose = choose;
            this.choose_context = choose_context;
        }

        private String choose;
        private String choose_context;
    }

}
